import 'dart:convert';
import 'dart:async';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:logging/logging.dart';

/// Gitee 服务类，用于从 Gitee 仓库获取 JSON 文件
class GiteeService {
  static final GiteeService _instance = GiteeService._internal();
  factory GiteeService() => _instance;
  GiteeService._internal();

  // Gitee 仓库信息
  static const String _owner = "hx611";
  static const String _repo = "application-configuration";
  static const String _branch = "master";
static final Logger AppLogger = Logger('GiteeService');
  /// 从 Gitee 仓库获取 Configuration.json 文件内容
  /// https://gitee.com/hx611/application-configuration/
  /// 返回解析后的 JSON 对象
Future<Map<String, dynamic>?> getConfigurationJson() async {
  final String rawUrl = "https://gitee.com/$_owner/$_repo/raw/$_branch/Configuration.json";

  try {
    AppLogger.info('正在从 Gitee 获取 Configuration.json 文件: $rawUrl');
    
    final response = await http.get(
      Uri.parse(rawUrl),
    ).timeout(
      const Duration(seconds: 30),
      onTimeout: () {
        throw TimeoutException('请求超时', const Duration(seconds: 30));
      },
    );

    if (response.statusCode == 200) {
      // 检查是否是 JSON
      if (response.headers['content-type']?.contains('application/json') ?? false) {
        final jsonData = json.decode(response.body);
        AppLogger.info('成功获取并解析 Configuration.json 文件');
        return jsonData;
      } else {
        throw HttpException('返回的不是 JSON 数据');
      }
    } else {
      AppLogger.warning('获取失败: HTTP ${response.statusCode}');
      throw HttpException('HTTP ${response.statusCode}');
    }
  } on SocketException catch (e) {
    AppLogger.warning('网络错误: $e');
    throw e;
  } on TimeoutException catch (e) {
    AppLogger.warning('请求超时: $e');
    throw e;
  } catch (e) {
    AppLogger.warning('未知错误: $e');
    rethrow;
  }
}
  /// 获取 README.md 文件内容
  ///
  /// 返回文件内容字符串
  Future<String?> getReadmeContent() async {
    final String rawUrl =
        "https://gitee.com/$_owner/$_repo/raw/$_branch/README.md";

    try {
      AppLogger.info('正在从 Gitee 获取 README.md 文件: $rawUrl');
      
      final response = await http.get(
        Uri.parse(rawUrl),
      ).timeout(
        const Duration(seconds: 30),
        onTimeout: () {
          throw TimeoutException('请求超时', const Duration(seconds: 30));
        },
      );

      if (response.statusCode == 200) {
        AppLogger.info('成功获取 README.md 文件');
        return response.body;
      } else {
        AppLogger.warning(
            '获取 README.md 文件失败: 状态码 ${response.statusCode}, 响应: ${response.body}');
        throw HttpException(
            '获取文件失败: 状态码 ${response.statusCode}, 响应: ${response.body}');
      }
    } on SocketException catch (e) {
      AppLogger.warning('网络不可用: $e');
      throw e;
    } on TimeoutException catch (e) {
      AppLogger.warning('请求超时: $e');
      throw e;
    } on HttpException catch (e) {
      AppLogger.warning('HTTP异常: $e');
      throw e;
    } catch (e) {
      AppLogger.warning('获取 Gitee README.md 文件时出错: $e');
      rethrow;
    }
  }

  /// 检查 Configuration.json 文件是否存在
  ///
  /// 返回文件是否存在
  Future<bool> isConfigurationExists() async {
    final String rawUrl =
        "https://gitee.com/$_owner/$_repo/raw/$_branch/Configuration.json";

    try {
      AppLogger.info('正在检查 Gitee Configuration.json 文件是否存在: $rawUrl');
      
      final response = await http.head(
        Uri.parse(rawUrl),
      ).timeout(
        const Duration(seconds: 10),
        onTimeout: () {
          throw TimeoutException('请求超时', const Duration(seconds: 10));
        },
      );

      return response.statusCode == 200;
    } catch (e) {
      AppLogger.warning('检查 Gitee Configuration.json 文件存在性时出错: $e');
      return false;
    }
  }
}